﻿using GalaSoft.MvvmLight;
using HRM.Model;
using GalaSoft.MvvmLight.Ioc;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Command;

namespace HRM.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class ChooseGroupViewModel : ViewModelBase
    {
        private IUserService _service;
        private IEntityService<NhomNguoiDung> _groupService;
        /// <summary>
        /// Initializes a new instance of the ChooseGroupViewModel class.
        /// </summary>
        public ChooseGroupViewModel(IUserService service, IEntityService<NhomNguoiDung> groupService)
        {
            _service = service;
            _groupService = groupService;
            if (SimpleIoc.Default.IsRegistered<List<NhomNguoiDung>>()) GroupUsers = SimpleIoc.Default.GetInstance<List<NhomNguoiDung>>();
            if (SimpleIoc.Default.IsRegistered<NhomNguoiDung>("CurrentGroup")) SelectedItem = SimpleIoc.Default.GetInstance<NhomNguoiDung>("CurrentGroup");
            if(SimpleIoc.Default.IsRegistered<NguoiSuDung>("User")) User = SimpleIoc.Default.GetInstance<NguoiSuDung>("User");
        }

        public NguoiSuDung User { get; private set; }

        public List<NhomNguoiDung> GroupUsers { get; private set; }

        private NhomNguoiDung _selectedItem;

        public NhomNguoiDung SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (_selectedItem != value)
                {
                    _selectedItem = value;
                    RaisePropertyChanged("SelectedItem");
                }
            }
        }

        public RelayCommand SaveCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (_service.UpdateGroup(User.MaNhanVien, SelectedItem.MaNhom))
                    {
                        SimpleIoc.Default.Unregister<NhomNguoiDung>("CurrentGroup");
                        SimpleIoc.Default.Unregister<NguoiSuDung>("User");
                        App.Current.MainWindow.Close();
                        var vm = SimpleIoc.Default.GetInstance<GroupUserViewModel>();
                        vm.Refresh();
                    }
                });
            }
        }

        public RelayCommand CancelCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    SimpleIoc.Default.Unregister<NhomNguoiDung>("CurrentGroup");
                    SimpleIoc.Default.Unregister<NguoiSuDung>("User");
                    App.Current.MainWindow.Close();
                });
            }
        }
    }
}